package com.zzb.projectfactory.framework.param.service;

import com.alibaba.fastjson.JSON;
import com.zzb.projectfactory.framework.param.dao.SysParamDAO;
import com.zzb.projectfactory.framework.param.dao.jpa.SysParamRepository;
import com.zzb.projectfactory.framework.param.entity.SysParam;
import com.zzb.projectfactory.framework.role.entity.User;
import com.zzb.projectfactory.framework.common.BaseResponse;
import com.zzb.projectfactory.framework.common.BaseService;
import com.zzb.projectfactory.framework.common.ServiceException;
import com.zzb.projectfactory.framework.utils.StringToTTypeUtil;
import com.zzb.projectfactory.framework.validator.annotation.ValidatorEnabled;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* 系统配置表 service类
*/
@Service("sysParamService")
public class SysParamService extends BaseService<SysParamDAO,SysParam,SysParamRepository> {
    private static final Logger logger = LoggerFactory.getLogger(SysParamService.class);
    @Autowired
    private SysParamDAO sysParamDAO;
    @Override
    public SysParamDAO getDAO() {
        return sysParamDAO;
    }
    /**删除系统配置表*/
    public BaseResponse deleteSysParam(String id,User operate) throws ServiceException {
        //TODO 删除应该不仅仅这么简单的操作，后面想到了再加 ZZB 20170222
        return delete(id);
    }
    /**保存系统配置表*/
    @ValidatorEnabled
    public BaseResponse<SysParam> saveSysParam(SysParam sysParam, User operator) throws ServiceException{
        logger.info("正在保存系统配置表["+ JSON.toJSONString(sysParam)+"]["+JSON.toJSONString(operator)+"]");
        //TODO 保存应该不仅仅这么简单的操作，后面想到了再加 ZZB 20170222
        return createOrUpdate(sysParam,operator);
    }

    /**获取参数值，如果没有找到配置，则返回空*/
    public <T> T get(String paramName,Class<T> clazz){
        SysParam sysParam = getDAO().getRepository().findTopByParamNameAndActivateOrderByCreateTimeDesc(paramName, true);
        return sysParam != null?StringToTTypeUtil.convert(sysParam.getParamValue(),clazz):null;
    }

    /** 获取参数值，如果没有找到配置，则返回默认值 */
    public <T> T get(String paramName,Class<T> clazz,T defaultValue){
        SysParam sysParam = getDAO().getRepository().findTopByParamNameAndActivateOrderByCreateTimeDesc(paramName, true);
        return sysParam != null?StringToTTypeUtil.convert(sysParam.getParamValue(),clazz):defaultValue;
    }


    /**获取参数值*/
    public String getString(String paramName,String defaultValue){
        SysParam sysParam = getDAO().getRepository().findTopByParamNameAndActivateOrderByCreateTimeDesc(paramName, true);
        return sysParam != null?sysParam.getParamValue():defaultValue;
    }

}
